package com.jack.redismq.config;

import com.jack.redismq.consumer.RedisListener;
import com.jack.redismq.util.RedisObjectSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created by zhang_j on 2019/12/3
 */
@Configuration
public class RedisConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class);

    /**
     * RedisTemplate解决乱码问题
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){
        LOGGER.info("redis序列化配置开始");
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        //string序列化方式
//        RedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
        RedisObjectSerializer redisObjectSerializer = new RedisObjectSerializer();

        //设置默认序列化方式
        template.setDefaultSerializer(redisObjectSerializer);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(redisObjectSerializer);
        LOGGER.info("redis序列化配置结束");

        return template;
    }

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        container.addMessageListener(new RedisListener(),new PatternTopic("demo-channel"));
        return container;
    }
}
